package com.nixsolutions.dao;

import com.nixsolutions.bean.Role;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author yakimovich
 */
@Repository
public class HibernateRoleDao implements RoleDao {

    @Autowired
    private SessionFactory sessionFactory;

    public HibernateRoleDao() {
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void create(Role role) {

        getCurrentSession().save(role);
    }

    @Override
    public void update(Role role) {

        getCurrentSession().update(role);
    }

    @Override
    public void remove(Role role) {

        getCurrentSession().delete(role);

    }

    @Override
    @SuppressWarnings("unchecked")
    public Role findByName(String name) {

        Role role = null;

        Criteria criteria 
                = getCurrentSession().createCriteria(Role.class);
        criteria.add(Restrictions.eq("name", name));
        List<Role> roles = criteria.list();

        if (!roles.isEmpty()) {
            role = roles.get(0);
        }
        return role;
    }
}